package com.kws.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.core.utils.bean.BeanUtils;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.PowerStationEntity;
import com.kws.merchant.domain.TradePowerStationEntity;
import com.kws.merchant.domain.po.MinePowerStationPo;
import com.kws.merchant.domain.po.PowerStationPo;
import com.kws.merchant.domain.vo.PowerStationVo;
import com.kws.merchant.mapper.PowerStationMapper;
import com.kws.merchant.service.PowerStationService;
import com.kws.merchant.service.TradePowerStationService;
import com.kws.merchant.util.Constant;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.domain.SysUser;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author : zhangbenting
 * @date : 2024/11/28 15:49
 * @Version: 1.0
 */
@Service
@Slf4j
public class PowerStationServiceImpl extends ServiceImpl<PowerStationMapper, PowerStationEntity> implements PowerStationService {

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    protected RestTemplate restTemplate;

    @Autowired
    private TradePowerStationService tradePowerStationService;

    public synchronized <T> Object postByModelExchange(String url, Map<String, String> headerMap, T t, Class<?> resp) {
        HttpHeaders httpHeaders = this.commonHeader();
        for (Map.Entry<String, String> stringStringEntry : headerMap.entrySet()) {
            httpHeaders.add(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
        httpHeaders.add("Content-Type", "application/json");
        HttpEntity httpEntity = new HttpEntity(t, httpHeaders);
        ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, httpEntity, resp);
        return result.getBody();
    }

    public HttpHeaders commonHeader() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Content-Type-Options", "nosniff");
        httpHeaders.add("X-Frame-Options", "DENY");
        httpHeaders.add("X-XSS-Protection", "1;mode=block");
        return httpHeaders;
    }

    public static Map<String, String> InitHashMap() {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json; charset=utf-8");
        return headerMap;
    }

    @Override
    public Page<PowerStationVo> minePowerStation(PowerStationPo powerStationPo) {
        // 获取当前登录用户
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Map<String, String> map = InitHashMap();
        JSONObject body = new JSONObject();
//        body.put("project_type",powerStationPo.getItemType());
        if (powerStationPo.getItemName() != null) {
            body.put("search_str", powerStationPo.getItemName());
        }
        body.put("user_id", userId);
        body.put("page_size", powerStationPo.getTotalPage());
        body.put("page_num", powerStationPo.getPageSize());
        Object o = postByModelExchange(Constant.DZLB, map, body, Object.class);
        if (o != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
            if (!jsonObject.getInteger("code").equals(200)) {
                log.info("获取微网数据失败：" + jsonObject.toJSONString());
            } else {
                JSONObject data = jsonObject.getJSONObject("data");
                Page<PowerStationVo> page = new Page<>(powerStationPo.getPageSize()
                        , powerStationPo.getTotalPage(), data.getInteger("total"));
                JSONArray dataList = data.getJSONArray("project_list");
                if (dataList != null && dataList.size() > 0) {
                    List<JSONObject> jsonObjects = JSON.parseArray(JSON.toJSONString(dataList), JSONObject.class);
                    List<PowerStationVo> powerStationEntities = new ArrayList<>();
                    List<PowerStationEntity> list = this.list();
                    Map<Integer, List<PowerStationEntity>> listMap = list.stream().collect(Collectors.groupingBy(PowerStationEntity::getCid));
                    for (JSONObject object : jsonObjects) {
                        PowerStationVo powerStationEntity = new PowerStationVo();
                        powerStationEntity.setStationName(object.getString("fullname"));
                        powerStationEntity.setStationAddress(object.getString("address"));
                        powerStationEntity.setStationId(object.getString("cid"));
                        powerStationEntity.setStationDirector(object.getString("principal"));
                        powerStationEntity.setPhone(object.getString("principal_phone"));
                        powerStationEntity.setStationType(object.getInteger("project_type"));
                        List<PowerStationEntity> cid = listMap.get(object.getInteger("cid"));
                        if (cid != null && cid.size() > 0) {
                            powerStationEntity.setStationImg(fileUtil.fixFileName()+cid.get(0).getStationImg());
                        }
                        powerStationEntities.add(powerStationEntity);
                    }
                    page.setRecords(powerStationEntities);
                    return page;
                }
            }
        }
        return new Page<PowerStationVo>();
    }

    @Override
    public boolean addPowerStation(MinePowerStationPo minePowerStationPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        Map<String, String> map = InitHashMap();
        JSONObject body = new JSONObject();
        body.put("user_id", userId);
        body.put("company_no", minePowerStationPo.getStationNumber());
        body.put("company_name", minePowerStationPo.getStationName());
        body.put("project_type", minePowerStationPo.getStationType());
        body.put("volume", minePowerStationPo.getCapacity());
        body.put("principal", minePowerStationPo.getStationDirector());
        body.put("contact", minePowerStationPo.getPhone());
        body.put("address", minePowerStationPo.getStationAddress());
        //todo 暂时写死
        ArrayList<String> strings = new ArrayList<>();
        strings.add("\\u5317\\u4eac\\u5e02");
        strings.add("\\u5317\\u4eac\\u5e02");
        strings.add("\\u4e1c\\u57ce\\u533a");
        body.put("area_names", strings);
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(110000);
        integers.add(110100);
        integers.add(110101);
        body.put("area_codes", integers);
        if (minePowerStationPo.getArea() != null) {
            body.put("area", minePowerStationPo.getArea());
        }
        if (minePowerStationPo.getCost() != null) {
            body.put("cost", minePowerStationPo.getCost());
        }
        Object o = postByModelExchange(Constant.XZDZ, map, body, Object.class);
        if (o != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
            if (!jsonObject.getInteger("code").equals(200)) {
                log.info("获取微网数据失败：" + jsonObject.toJSONString());
            } else {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONObject object = data.getJSONObject("data");
                Integer cid = object.getInteger("cid");
                PowerStationEntity powerStationEntity = new PowerStationEntity();
                powerStationEntity.setUserId(userId);
                powerStationEntity.setCid(cid);
                powerStationEntity.setEnable("1");
                powerStationEntity.setStationImg(minePowerStationPo.getStationImg());
                return this.save(powerStationEntity);
            }
        }
        return false;
    }

    @Override
    public boolean applyTradePowerStation(Integer powerStationId) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<TradePowerStationEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TradePowerStationEntity::getStationId, powerStationId);
        long count = tradePowerStationService.count(wrapper);
        if (count > 0) {
            throw new RuntimeException("该电站已申请售卖，请勿重复申请！");
        }
        PowerStationEntity powerStationEntity = this.getOne(Wrappers.<PowerStationEntity>lambdaQuery().eq(PowerStationEntity::getCid, powerStationId));
        TradePowerStationEntity tradePowerStation = new TradePowerStationEntity();
        tradePowerStation.setUserId(userId);
        tradePowerStation.setStationId(Long.valueOf(powerStationId));
        if (powerStationEntity != null){
            tradePowerStation.setStationImg(powerStationEntity.getStationImg());
        }
        JSONObject body = new JSONObject();
        body.put("user_id", userId);
        Map<String, String> map = InitHashMap();
        Object o = postByModelExchange(Constant.DZLB, map, body, Object.class);
        if (o != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
            if (!jsonObject.getInteger("code").equals(200)) {
                log.info("获取微网数据失败：" + jsonObject.toJSONString());
            } else {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray dataList = data.getJSONArray("project_list");
                if (dataList != null && dataList.size() > 0) {
                    List<JSONObject> jsonObjects = JSON.parseArray(JSON.toJSONString(dataList), JSONObject.class);
                    JSONObject cid = jsonObjects.stream().filter(p -> p.getInteger("cid")
                            .equals(powerStationId)).findFirst().orElse(null);
                    if (ObjectUtils.isNull(cid)) {
                        throw new RuntimeException("该电站不存在");
                    }
                    tradePowerStation.setStationAddress(cid.getString("address"));
                    tradePowerStation.setStationName(cid.getString("fullname"));
                    tradePowerStation.setStationDescribe(cid.getString("principal"));
                }
            }
        }
        tradePowerStation.setEnable("1");
        return tradePowerStationService.save(tradePowerStation);
    }


}
